package org.example.dialogue.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.example.ai.result.Result;
import org.example.dialogue.form.MessageForm;
import org.example.dialogue.mapper.ServiceConversationsMapper;
import org.example.dialogue.mapper.ServiceMessageUserMapper;
import org.example.dialogue.pojo.Conversations;
import org.example.dialogue.pojo.MessagesUser;
import org.example.dialogue.service.ServiceMessageUser;
import org.example.dialogue.vo.MessageVo;
import org.example.dialogue.config.ErnieProperties;
import org.example.dialogue.config.TokenResponse;
import org.example.dialogue.service.ServiceDialogueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zqtao
 */

@Service
public class ServiceDialogueServiceImpl implements ServiceDialogueService {

    @Autowired
    private ErnieProperties ernieProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ServiceConversationsMapper conversationsMapper;

    @Autowired
    private ServiceMessageUserMapper serviceMessageUser;

    @Override
    public List<MessageVo> getMessage(List<MessageForm> messageForms, Long userId, Integer initValue) {


        try {

            int size = messageForms.size();

            MessageForm messageForm = messageForms.get(size-1);

            if (size==1){
                setTitle(initValue, messageForm.getContent());
            }

            MessagesUser messagesUser = new MessagesUser();
            messagesUser.setConversationId(initValue);
            messagesUser.setSenderType(messageForm.getRole());
            messagesUser.setContent(messageForm.getContent());
            messagesUser.setSendTime(new Date());
            serviceMessageUser.insert(messagesUser);

            ObjectMapper mapper = new ObjectMapper();
            String messageFormsJson = mapper.writeValueAsString(messageForms);

            // 构建请求体
            String requestJson = String.format(
                    "{\"messages\":%s,\"temperature\":0.95,\"top_p\":0.8,\"penalty_score\":1," +
                            "\"enable_system_memory\":false,\"disable_search\":false,\"enable_citation\":false}",
                    messageFormsJson
            );

            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, requestJson);

            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=24.43ce4d9f0b44c7ef522d46f356648aa5.2592000.1739677651.282335-117103049")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(300, TimeUnit.SECONDS)
                    .readTimeout(300, TimeUnit.SECONDS)
                    .writeTimeout(300, TimeUnit.SECONDS)
                    .build();

            try (Response response = okHttpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    throw new RuntimeException("API调用失败: " + response.code());
                }

                String responseBody = response.body().string();

                // 解析文心一言API的响应
                JsonNode rootNode = mapper.readTree(responseBody);

                // 创建MessageVo对象
                MessageVo messageVo = new MessageVo();
                if (rootNode.has("result")) {
                    messageVo.setContent(rootNode.get("result").asText());
                    // 设置其他必要的字段
                    messageVo.setRole("assistant");
                    // messageVo.setName("AI助手");
                    // 如果需要设置其他字段，在这里设置
                } else {
                    throw new RuntimeException("API响应中没有result字段: " + responseBody);
                }

                String key = "chat:message";

                List<MessageVo> messageVos = Collections.singletonList(messageVo);

                MessagesUser messagesUser2 = new MessagesUser();

                MessageVo messageVo1 = messageVos.get(0);

                messagesUser2.setConversationId(initValue);
                messagesUser2.setSenderType(messageVo1.getRole());
                messagesUser2.setContent(messageVo1.getContent());
                messagesUser2.setSendTime(new Date());
                serviceMessageUser.insert(messagesUser2);

                messageForms.add(new MessageForm(messageVos.get(0).getRole(),messageVos.get(0).getContent()));

                redisTemplate.opsForValue().set(key, messageForms);

                // 返回包含单个消息的列表
                return Collections.singletonList(messageVo);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON处理错误", e);
        } catch (IOException e) {
            throw new RuntimeException("网络请求错误", e);
        }
    }

    private void setTitle(Integer initValue, String content) {
        Conversations conversations = conversationsMapper.selectById(initValue);
        conversations.setTitle(content);
        conversationsMapper.updateById(conversations);
    }

    @Override
    public String saveMessage(Long userId) {

        String jsonString = JSON.toJSONString(redisTemplate.opsForValue().get("chat:message"));

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            List<MessageForm> messageVoList = objectMapper.readValue(jsonString, new TypeReference<List<MessageForm>>() {});
            MessagesUser messagesUser = new MessagesUser();
            messageVoList.forEach(messageForm -> {
            });


        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    @Override
    public Integer initializeChat(Long userId) {
        Conversations conversations = new Conversations();
        conversations.setUserId(userId);
        conversations.setStartTime(new Date());
        conversations.setImage("https://jiyunzjy.oss-cn-beijing.aliyuncs.com/%E7%94%9F%E6%88%90%E6%99%BA%E8%B6%A3%E5%B0%8F%E7%AA%9D%E5%9B%BE%E7%89%87.png");
        conversationsMapper.insert(conversations);
        return conversations.getConversationId();
    }

    @Override
    public String deleteChat(Integer conversationId) {
        LambdaQueryWrapper<MessagesUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MessagesUser::getConversationId,conversationId);
        int delete = serviceMessageUser.delete(wrapper);
        if(delete == 0){
            conversationsMapper.deleteById(conversationId);
        }
        return "删除成功";
    }


}
